package com.innovation.ic.b1b.monitor.base.service.masterSlave.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.monitor.base.mapper.ElasticsearchMapper;
import com.innovation.ic.b1b.monitor.base.model.Elasticsearch;
import com.innovation.ic.b1b.monitor.base.model.ElasticsearchAvailableJob;
import com.innovation.ic.b1b.monitor.base.pojo.ElasticsearchPojo;
import com.innovation.ic.b1b.monitor.base.pojo.constant.TableNameConstant;
import com.innovation.ic.b1b.monitor.base.pojo.variable.ServiceResult;
import com.innovation.ic.b1b.monitor.base.pojo.variable.elasticsearch.ElasticsearchQueryRespPojo;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ElasticsearchAvailableJobLogHistoryService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ElasticsearchAvailableJobLogService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ElasticsearchAvailableJobService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ElasticsearchService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.EnvironmentService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ServiceHelper;
import com.innovation.ic.b1b.monitor.base.vo.ElasticsearchVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ElasticsearchServiceImpl extends ServiceImpl<ElasticsearchMapper, Elasticsearch> implements ElasticsearchService {
    @Resource
    private EnvironmentService environmentService;

    @Resource
    private ElasticsearchAvailableJobService elasticsearchAvailableJobService;

    @Resource
    private ElasticsearchAvailableJobLogService elasticsearchAvailableJobLogService;

    @Resource
    private ElasticsearchAvailableJobLogHistoryService elasticsearchAvailableJobLogHistoryService;

    @Resource
    private ServiceHelper serviceHelper;


    @Override
    public ServiceResult addElasticsearch(ElasticsearchVo elasticsearchVo) {
        ServiceResult serviceResult = new ServiceResult();
        Integer id = elasticsearchVo.getId();
        Elasticsearch elasticsearch = new Elasticsearch();
        BeanUtil.copyProperties(elasticsearchVo, elasticsearch);
        QueryWrapper<Elasticsearch> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ip", elasticsearchVo.getIp());
        queryWrapper.eq("port", elasticsearchVo.getPort());
        if (id == null) {
            List<Elasticsearch> environments = this.baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(environments)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("重复,请重新添加");
                return serviceResult;
            }

            QueryWrapper<Elasticsearch> queryWrapperName = new QueryWrapper<>();
            queryWrapperName.eq("name", elasticsearchVo.getName());
            List<Elasticsearch> esNameList = this.baseMapper.selectList(queryWrapperName);
            if (!CollectionUtils.isEmpty(esNameList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("名字不能重复");
                return serviceResult;
            }


            this.baseMapper.insert(elasticsearch);
        } else {
            queryWrapper.ne("id", id);
            List<Elasticsearch> environments = this.baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(environments)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("重复,请重新添加");
                return serviceResult;
            }

            QueryWrapper<Elasticsearch> queryWrapperName = new QueryWrapper<>();
            queryWrapperName.eq("name", elasticsearchVo.getName());
            queryWrapperName.ne("id", id);
            List<Elasticsearch> esNameList = this.baseMapper.selectList(queryWrapperName);
            if (!CollectionUtils.isEmpty(esNameList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("名字不能重复");
                return serviceResult;
            }

            this.baseMapper.updateById(elasticsearch);
        }
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage("成功");
        return serviceResult;
    }

    @Override
    public void deleteElasticsearch(ElasticsearchVo elasticsearchVo) {
        Integer id = elasticsearchVo.getId();
        this.baseMapper.deleteById(id);
        this.deleteByESId(id);
    }

    @Override
    public ServiceResult<PageInfo<ElasticsearchPojo>> findByPage(ElasticsearchVo elasticsearchVo,Boolean mainDb) {
        ServiceResult<PageInfo<ElasticsearchPojo>> serviceResult = new ServiceResult<>();
        Integer environmentId = elasticsearchVo.getEnvironmentId();
        if (environmentId != null) {
            List<Integer> environmentIds = environmentService.findByName(environmentId);
            if (!CollectionUtils.isEmpty(environmentIds)) {
                elasticsearchVo.setEnvironmentIds(environmentIds);
            }
        }
        PageHelper.startPage(elasticsearchVo.getPageNo(), elasticsearchVo.getPageSize());
        List<ElasticsearchPojo> environmentPojoList = this.baseMapper.findByPage(elasticsearchVo);
        PageInfo<ElasticsearchPojo> pageInfo = new PageInfo<>(environmentPojoList);
        serviceResult.setResult(pageInfo);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 查询es列表
     *
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<ElasticsearchQueryRespPojo>> queryServerInfoList(Boolean mainDb) {
        List<ElasticsearchQueryRespPojo> result = this.baseMapper.queryServerInfoList();
        ServiceResult<List<ElasticsearchQueryRespPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByEnvironmentId(Integer id) {
        QueryWrapper<Elasticsearch> queryWrapper = new QueryWrapper();
        queryWrapper.eq("environment_id", id);
        List<Elasticsearch> elasticsearches = this.baseMapper.selectList(queryWrapper);
        for (Elasticsearch elasticsearch : elasticsearches) {
            this.deleteByESId(elasticsearch.getId());
        }
        Map<String, Object> param = new HashMap<>();
        param.put("environment_id", id);
        this.baseMapper.deleteByMap(param);
    }


    /**
     * 关联删除
     *
     * @param esId
     */
    private void deleteByESId(Integer esId) {
        List<ElasticsearchAvailableJob> elasticsearchAvailableJobList = elasticsearchAvailableJobService.findByElasticsearchId(esId);
        for (ElasticsearchAvailableJob elasticsearchAvailableJob : elasticsearchAvailableJobList) {
            Integer elasticsearchAvailableJobId = elasticsearchAvailableJob.getId();
            //删除定时任务
            elasticsearchAvailableJobService.delete(elasticsearchAvailableJobId);
            String jobId = TableNameConstant.ELASTICSEARCH_AVAILABLE_JOB + "_" + elasticsearchAvailableJobId;
            serviceHelper.getQuartzManager().deleteScheduleJob(jobId);
            //删除日志以及历史日志
            elasticsearchAvailableJobLogService.deleteByElasticsearchAvailableJobId(elasticsearchAvailableJobId);
            elasticsearchAvailableJobLogHistoryService.deleteByElasticsearchAvailableJobId(elasticsearchAvailableJobId);
        }
    }

}